package com.atguigu.srb.core.controller.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;


public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {
    private static final int COUNT = 30;
    DictMapper dictMapperListener;
    List<Dict> list = new ArrayList<>();

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapperListener = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        System.out.println("读到一行");
        //new一个Dict对象备用
        Dict dict = new Dict();
        //利用BeanUtils工具类的copyProperties方法将excelDictDTO中的属性复制到dict中
        BeanUtils.copyProperties(excelDictDTO,dict);
        //将带有excel表格数据的dict添加到list集合中
        list.add(dict);
        System.out.println(list);
        //调用dictMapperListener中的insertBatch方法批量添加COUNT条数据,并清空list集合
        if (list.size()>=COUNT){
            dictMapperListener.insertBatch(list);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("读完");
        dictMapperListener.insertBatch(list);
    }

}
